package com.lc.code.service.impl;

import com.lc.code.dao.CodeMapper;
import com.lc.code.pojo.CodeRecord;
import com.lc.code.service.CodeService;
import com.lc.code.service.EmailFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.ThreadLocalRandom;

@Service
public class CodeServiceImpl implements CodeService {

    @Autowired
    private CodeMapper codeMapper;
    @Autowired
    private EmailFeign emailFeign;
    private char[] chars = new char[]{'0','1','2','3','4','5','6','7','8','9'};
    private long TEN_MINUTE = 600000;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean genCode(String email) {
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < 6; ++i){
            sb.append(chars[ThreadLocalRandom.current().nextInt(9)]);
        }
        CodeRecord codeRecord = new CodeRecord();
        codeRecord.setEmail(email);
        codeRecord.setCode(sb.toString());
        codeMapper.insert(codeRecord);
        //发送email
        boolean res = emailFeign.send(email,codeRecord.getCode());
        return res;
    }

    @Override
    public int validateCode(String email,String code) {
        CodeRecord last = codeMapper.getLast(email);
        if(last.getCreateTime().getTime() - System.currentTimeMillis() > TEN_MINUTE){
            //超时
            return 2;
        }
        if(code.equals(last.getCode())){
            //正确
            return 0;
        }
        //错误
        return 1;
    }
}
